﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ccit.Utils;
using Ccit.SysPlat.Log;
using Ccit.ClassLibrary;
using System.Text;
using System.Data;
using Ccit.SysPlat.Organ;

namespace Ccit.SysPlat.Purview
{
    /// <summary>
    /// Description: 系统平台权限菜单 -> 角色管理ACCESS数据实现层
    /// Author: tim 2010-03-04
    /// </summary>
    public class RoleAES : IRole
    {
        #region init error log interface
        private ILog _logInterface = null;
        private const string _funcPageName = "角色管理";
        public RoleAES()
        {
            _logInterface = Factory.CreateObject(MsErrLog.assemblyName, MsErrLog.className, 
                                                    ImportComponentType.DotNetDll, null) as ILog;
        }        
        #endregion

        #region IRole 成员

        public List<string> Delete(string roleId)
        {
            List<string> lstCmdText = new List<string>();
            string cmdText = string.Empty;

            cmdText = "UPDATE PUR_A1 SET PUR_A1_70='1' WHERE PUR_A1_10=" + roleId;
            lstCmdText.Add(cmdText);

            cmdText = "DELETE FROM PUR_R3 WHERE PUR_R3_10=" + roleId;
            lstCmdText.Add(cmdText);

            cmdText = "DELETE FROM PUR_R2 WHERE PUR_R2_10=" + roleId;
            lstCmdText.Add(cmdText);

            try {
                int iexe = DataAccessor.ExecuteNonQuery(lstCmdText);
                if (iexe > 0) return new List<string> { roleId, "删除成功!" };
                else return new List<string> { "-1", "操作失败:服务器忙请稍后重新尝试操作!" };
            }
            catch (Exception ex)
            {
                StringBuilder sbParam = new StringBuilder();
                int sqlIndex = 1;
                foreach (string eSQL in lstCmdText)
                {
                    sbParam.Append("<SQL" + sqlIndex.ToString()).Append("><![CDATA[").Append(eSQL);
                    sbParam.Append("]]></SQL" + sqlIndex.ToString() + ">");
                    sqlIndex++;
                }
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = sbParam.ToString()
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                sbParam = null;
                return new List<string> { 
                    "-2",
                    "保存失败:详情请参见错误日志!"                    
                };
            }
        }

        public MsRole GetRoleInfo(string roleId)
        {
            if(string.IsNullOrEmpty(roleId)) return null;

            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT PUR_A1_10 AS ROLEID,PUR_A1_20 AS ROLENAME,PUR_A1_30 AS ROLEDESC,PUR_A1_40 AS RANGEIDS,PUR_A1_50 AS RANGETYPE,");
            sbCmdText.Append("PUR_A1_60 AS ROLETYPE,PUR_A1_70 AS EFFECT,PUR_A1_9994 AS CREATUSERID FROM PUR_A1 WHERE PUR_A1_10=").Append(roleId);

            MsLoginUser loginUser = HttpContext.Current.Session["LogUserInfo"] as MsLoginUser;
            MsRole msRole = null;
            string isCanEdit = "0"; //当前角色能否编辑
            try {
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    if(iReader.Read() && null != iReader[0])   
                        if(loginUser.userType != eUserType.ORDINARY) isCanEdit = "1"; //管理员可以编辑
                        else {
                            if(loginUser.userId.Equals(iReader["CREATUSERID"].ToString())) isCanEdit = "1";  //同一用户创建的角色也可以编辑
                            else isCanEdit = "0";
                        }
                        msRole = new MsRole {
                            roleId = iReader["ROLEID"].ToString(),
                            roleName = iReader["ROLENAME"].ToString(),
                            roleDesc = iReader["ROLEDESC"].ToString(),
                            rangeType = (!string.IsNullOrEmpty(iReader["RANGETYPE"].ToString())) ? 
                                        (eSysRangeType)Enum.Parse(typeof(eSysRangeType),iReader["RANGETYPE"].ToString()) : eSysRangeType.USER,
                            rangeIds = iReader["RANGEIDS"].ToString(),
                            sysRole = (eTrueFalse)Enum.Parse(typeof(eTrueFalse),iReader["ROLETYPE"].ToString()),
                            effect = iReader["EFFECT"].ToString(),
                            canEdit = (eTrueFalse)Enum.Parse(typeof(eTrueFalse),isCanEdit)
                        };
                }

                if(null != msRole)
                {   
                    string rangeNames = SysInterface.GetNameStrByIdStr(msRole.rangeIds,msRole.rangeType,eSeparator.ENTER,eTrueFalse.TRUE);
                    msRole.rangeNames = rangeNames;
                                        
                    // 获取角色的模块权限
                    msRole.modPrvIds = getModPrvIds(roleId);

                    // 获取角色操作权限
                    msRole.lstMenuPrv = getOperMenuPrvList(roleId);
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbCmdText = null;
            return msRole;
        }

        public List<MsRole> GetRoleList(string organId, eTrueFalse sysRole, string curUserId)
        {
            StringBuilder sbCmdText = new StringBuilder();

            sbCmdText.Append("SELECT PUR_A1_10 AS ROLEID,PUR_A1_20 AS ROLENAME,PUR_A1_9994 AS CREATEUSER FROM PUR_A1 ");
            sbCmdText.Append("WHERE PUR_A1_60='").Append(sysRole.ToString("D")).Append("' AND PUR_A1_70='0' AND PUR_A1_9990=").Append(organId);

            List<MsRole> lstRole = new List<MsRole>();
            try
            {
                MsRole msRole;
                string isCanEdit = string.Empty;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        isCanEdit = (curUserId.Equals(iReader["CREATEUSER"].ToString())) ? "1" : "0";
                        msRole = new MsRole
                        {
                            roleId = iReader["ROLEID"].ToString(),
                            roleName = iReader["ROLENAME"].ToString(),
                            canEdit = (eTrueFalse)Enum.Parse(typeof(eTrueFalse), isCanEdit)
                        };
                        lstRole.Add(msRole);
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            return lstRole;
        }

        public bool IsExistSameName(string roleId, string roleName, string organId, eTrueFalse sysRole)
        {
            string cmdText = "SELECT PUR_A1_10 AS ROLEID FROM PUR_A1 WHERE PUR_A1_20='" + roleName + "' AND PUR_A1_60='" + sysRole.ToString("D") +
                             "' AND PUR_A1_9990=" + organId;

            string recRoleId = string.Empty;
            try
            {
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    if (iReader.Read() && null != iReader[0])
                        recRoleId = iReader["ROLEID"].ToString();
                }

                if (string.IsNullOrEmpty(recRoleId)) return false;
                else if (string.IsNullOrEmpty(roleId)) return true;
                else
                {
                    if (recRoleId.Equals(roleId)) return false;
                    else return true;
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                return true;
            }
        }

        public List<string> Save(MsRole msRole)
        {
            if (null == msRole) return new List<string> { "-999", "保存失败:缺少必要参数!" };

            string roleId = msRole.roleId;
            if (string.IsNullOrEmpty(roleId)) return addnew(msRole);
            else return update(msRole);
        }

        public List<MsMenu> GetModAdminMenus(string userId,string organId)
        {
            if (string.IsNullOrEmpty(userId)) return new List<MsMenu>();

            string roleIds = GetRoleIdsByUserId(userId,eUserType.ORDINARY, organId);
            if (string.IsNullOrEmpty(roleIds)) return new List<MsMenu>();

            #region 获取该用户所具有管理权限的模块
            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT PUR_B1_10 AS MENUID,PUR_B1_20 AS MENUNAME,PUR_B1_30 AS LAYCODE ");
            sbCmdText.Append("FROM PUR_B1 WHERE PUR_B1_10 IN(SELECT PUR_R3_20 FROM PUR_R3 WHERE PUR_R3_10 IN (").Append(roleIds).Append(")) ");
            sbCmdText.Append("AND PUR_B1_50='0' AND PUR_B1_140='0' ORDER BY PUR_B1_80 ASC,PUR_B1_40 ASC");

            List<MsMenu> lstModMenu = new List<MsMenu>();
            string sysMenuClause = string.Empty;  //获取系统模块菜单的子菜单条件语句
            string qryClause = string.Empty;
            try
            {
                MsMenu msMenu;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        msMenu = new MsMenu
                        {
                            menuId = iReader["MENUID"].ToString(),
                            menuName = iReader["MENUNAME"].ToString(),
                            layCode = iReader["LAYCODE"].ToString(),
                            lay = "1"
                        };
                        lstModMenu.Add(msMenu);

                        qryClause = "(PUR_B1_30 LIKE '" + iReader["LAYCODE"].ToString() + "%' AND LEN(PUR_B1_30)>6)";
                        sysMenuClause += (string.IsNullOrEmpty(sysMenuClause)) ? qryClause : " OR " + qryClause;

                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                return lstModMenu;  //出现异常则返回
            }

            #endregion

            #region 获取模块下的子菜单
            if (!string.IsNullOrEmpty(sysMenuClause))
            {
                sbCmdText.Remove(0, sbCmdText.ToString().Length);
                sbCmdText.Append("SELECT PUR_B1_10 AS MENUID,PUR_B1_20 AS MENUNAME,PUR_B1_30 AS LAYCODE,PUR_B1_90 AS LEAF,");
                sbCmdText.Append("PUR_B1_100 AS PURVIEWSET,PUR_B1_120 AS RANGESET FROM PUR_B1 WHERE ");
                sbCmdText.Append(sysMenuClause).Append(" AND PUR_B1_50='0' AND PUR_B1_140='0' ORDER BY PUR_B1_30 ASC,PUR_B1_40 ASC");

                try
                {
                    MsMenu msSubMenu;
                    string isLeaf = string.Empty;
                    string purviewSet = string.Empty; //权限设置标志
                    string rangeSet = string.Empty; //范围设置标志
                    int layCodeLen = 0;
                    using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                    {
                        while (iReader.Read())
                        {
                            layCodeLen = iReader["LAYCODE"].ToString().Length / 6;
                            isLeaf = iReader["LEAF"].ToString();
                            if (layCodeLen == 2)
                            {
                                /* 业务逻辑
                                 *    非叶子节点的二级菜单不需要设置权限和数据范围
                                 *    它们能否展现完全取决于下级的叶子节点是否需要设置权限：
                                 *    如果没有需要设置权限的叶子节点，那么就不展现该二级菜单，如果所有的二级菜单都不展现，那么也就不展现模块菜单
                                 * tim 2010-03-08*/
                                purviewSet = (isLeaf == "1") ? iReader["PURVIEWSET"].ToString() : "0";
                                rangeSet = (isLeaf == "1") ? iReader["RANGESET"].ToString() : "0";
                            }
                            else
                            {
                                purviewSet = iReader["PURVIEWSET"].ToString();
                                rangeSet = iReader["RANGESET"].ToString();
                            }

                            msSubMenu = new MsMenu
                            {
                                menuId = iReader["MENUID"].ToString(),
                                menuName = iReader["MENUNAME"].ToString(),
                                layCode = iReader["LAYCODE"].ToString(),
                                isLeaf = isLeaf,
                                purviewSet = purviewSet,
                                rangeSet = rangeSet,
                                lay = layCodeLen.ToString()
                            };
                            lstModMenu.Add(msSubMenu);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MsErrLog msErrorLog = new MsErrLog
                    {
                        funcPageName = _funcPageName,
                        errMsg = ex.Message,
                        codeTrack = ex.StackTrace,
                        errClassCode = "001", //SQL 异常
                        paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                    };

                    _logInterface.WriteErrorLog(msErrorLog);
                    msErrorLog = null;
                    return lstModMenu;  //出现异常则返回
                }
            }

            #endregion

            sbCmdText = null;
            return lstModMenu;
        }

        public List<MsMenu> GetSysAdminMenus(string organId)
        {
            StringBuilder sbCmdText = new StringBuilder();

            #region 获取系统菜单中所有有效的1级菜单
            sbCmdText.Append("SELECT PUR_B1_10 AS MENUID,PUR_B1_20 AS MENUNAME,PUR_B1_30 AS LAYCODE,PUR_B1_80 AS SYSSIGN ");
            sbCmdText.Append("FROM PUR_B1 WHERE LEN(PUR_B1_30)=6 AND PUR_B1_50='0' AND PUR_B1_140='0' AND PUR_B1_9990=").Append(organId);
            sbCmdText.Append(" ORDER BY PUR_B1_80 ASC,PUR_B1_40 ASC");

            string sysMenuClause = string.Empty;  //获取系统模块菜单的子菜单条件语句
            string qryClause = string.Empty;
            List<MsMenu> lstModMenu = new List<MsMenu>();
            try
            {
                MsMenu msMenu;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        msMenu = new MsMenu
                        {
                            menuId = iReader["MENUID"].ToString(),
                            menuName = iReader["MENUNAME"].ToString(),
                            layCode = iReader["LAYCODE"].ToString(),
                            sysSign = iReader["SYSSIGN"].ToString(),
                            lay = "1"
                        };
                        lstModMenu.Add(msMenu);

                        if (iReader["SYSSIGN"].ToString() == "1")
                        {
                            qryClause = "(PUR_B1_30 LIKE '" + iReader["LAYCODE"].ToString() + "%' AND LEN(PUR_B1_30)>6)";
                            sysMenuClause += (string.IsNullOrEmpty(sysMenuClause)) ? qryClause : " OR " + qryClause;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                return lstModMenu;  //出现异常则返回
            }
            #endregion

            #region 获取模块菜单类型为系统的全部子集菜单
            if (!string.IsNullOrEmpty(sysMenuClause))
            {
                sbCmdText.Remove(0, sbCmdText.ToString().Length);
                sbCmdText.Append("SELECT PUR_B1_10 AS MENUID,PUR_B1_20 AS MENUNAME,PUR_B1_30 AS LAYCODE,PUR_B1_90 AS LEAF,");
                sbCmdText.Append("PUR_B1_100 AS PURVIEWSET,PUR_B1_120 AS RANGESET FROM PUR_B1 WHERE ");
                sbCmdText.Append(sysMenuClause).Append(" AND PUR_B1_50='0' AND PUR_B1_140='0' ORDER BY PUR_B1_30 ASC,PUR_B1_40 ASC");

                try
                {
                    MsMenu msSubMenu;
                    string isLeaf = string.Empty;
                    string purviewSet = string.Empty; //权限设置标志
                    string rangeSet = string.Empty; //范围设置标志
                    int layCodeLen = 0;
                    using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                    {
                        while (iReader.Read())
                        {
                            layCodeLen = iReader["LAYCODE"].ToString().Length / 6;
                            isLeaf = iReader["LEAF"].ToString();
                            if (layCodeLen == 2)
                            {
                                /* 业务逻辑
                                 *    非叶子节点的二级菜单不需要设置权限和数据范围
                                 *    它们能否展现完全取决于下级的叶子节点是否需要设置权限：
                                 *    如果没有需要设置权限的叶子节点，那么就不展现该二级菜单，如果所有的二级菜单都不展现，那么也就不展现模块菜单
                                 * tim 2010-03-08*/
                                purviewSet = (isLeaf == "1") ? iReader["PURVIEWSET"].ToString() : "0";
                                rangeSet = (isLeaf == "1") ? iReader["RANGESET"].ToString() : "0";
                            }
                            else
                            {
                                purviewSet = iReader["PURVIEWSET"].ToString();
                                rangeSet = iReader["RANGESET"].ToString();
                            }

                            msSubMenu = new MsMenu
                            {
                                menuId = iReader["MENUID"].ToString(),
                                menuName = iReader["MENUNAME"].ToString(),
                                layCode = iReader["LAYCODE"].ToString(),
                                isLeaf = isLeaf,
                                purviewSet = purviewSet,
                                rangeSet = rangeSet,
                                lay = layCodeLen.ToString()
                            };
                            lstModMenu.Add(msSubMenu);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MsErrLog msErrorLog = new MsErrLog
                    {
                        funcPageName = _funcPageName,
                        errMsg = ex.Message,
                        codeTrack = ex.StackTrace,
                        errClassCode = "001", //SQL 异常
                        paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                    };

                    _logInterface.WriteErrorLog(msErrorLog);
                    msErrorLog = null;
                    return lstModMenu;  //出现异常则返回
                }
            }


            IEnumerable<MsMenu> sysMenuQuery = lstModMenu.Where(m => m.sysSign == "1");
            foreach (MsMenu eMenu in sysMenuQuery)
            {

            }
            #endregion

            sbCmdText = null;
            return lstModMenu;
        }


        public string GetRoleIdsByUserId(string userId, eUserType enUserType, string organId)
        {
            if (enUserType == eUserType.ORDINARY) return getOrdinaryRoles(userId, organId);
            else return getAdminRoles();
        }

        #endregion


        #region private methods
        /// <summary>
        /// 根据角色Id获取角色对应的模块权限菜单Id串
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        private string getModPrvIds(string roleId)
        {
            string cmdText = "SELECT PUR_R3_20 AS MODMENUID FROM PUR_R3 WHERE PUR_R3_10=" + roleId;
            string modPrvIds = string.Empty;

            try
            {
                string modPrvId = string.Empty;
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while (iReader.Read())
                    {
                        modPrvId = iReader["MODMENUID"].ToString();
                        modPrvIds += (string.IsNullOrEmpty(modPrvIds)) ? modPrvId : "," + modPrvId;
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            return modPrvIds;
        }

        /// <summary>
        /// 获取角色所具有的操作菜单权限集合
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        private List<MsPurview> getOperMenuPrvList(string roleId)
        { 
            string cmdText = "SELECT PUR_R2_10 AS ROLEID,PUR_R2_20 AS MENUID,PUR_R2_30 AS DATARANGETYPE,PUR_R2_40 AS CUSTRANGETYPE,PUR_R2_50 AS CUSTRANGEIDS ";
            cmdText += "FROM PUR_R2 WHERE PUR_R2_10=" + roleId;

            List<MsPurview> lstPrv = new List<MsPurview>();
            try {
                MsPurview msPrv;
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while (iReader.Read())
                    {
                        msPrv = new MsPurview {
                            roleId = iReader["ROLEID"].ToString(),
                            menuId = iReader["MENUID"].ToString(),
                            rangeSign = iReader["DATARANGETYPE"].ToString(),
                            custRangeType = (!string.IsNullOrEmpty(iReader["CUSTRANGETYPE"].ToString())) ?
                                            (eSysRangeType)Enum.Parse(typeof(eSysRangeType),iReader["CUSTRANGETYPE"].ToString()) : eSysRangeType.USER,
                            custRangeIds = iReader["CUSTRANGEIDS"].ToString()
                        };

                        lstPrv.Add(msPrv);
                    }
                }

                //获取范围Ids对应的名称
                foreach(MsPurview ePrv in lstPrv)
                {                    
                    ePrv.custRangeNames = SysInterface.GetNameStrByIdStr(ePrv.custRangeIds,ePrv.custRangeType,eSeparator.COMMA);
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            return lstPrv;
        }
        

        /// <summary>
        /// 获取机构中的所有有效角色
        /// (包含角色的范围设置和Id)
        /// </summary>
        /// <param name="organId"></param>
        /// <returns></returns>
        private List<MsRole> getALLRole(string organId)
        {
            string cmdText = "SELECT PUR_A1_10 AS ROLEID,PUR_A1_40 AS RANGE,PUR_A1_50 AS RANGETYPE FROM PUR_A1 WHERE PUR_A1_70='0' AND PUR_A1_9990=" + organId;
            List<MsRole> lstRole = new List<MsRole>();

            try
            {
                MsRole msRole;
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while (iReader.Read())
                    {
                        msRole = new MsRole
                        {
                            roleId = iReader["ROLEID"].ToString(),
                            rangeType = (eSysRangeType)Enum.Parse(typeof(eSysRangeType), iReader["RANGETYPE"].ToString()),
                            rangeIds = iReader["RANGE"].ToString()
                        };
                        lstRole.Add(msRole);
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            return lstRole;
        }


        private List<string> addnew(MsRole msRole)
        {
            List<string> lstCmdText = new List<string>();
            StringBuilder sbCmdText = new StringBuilder();
            string[] sessionSQL = SessionExt.GetSysFieldSQL("PUR_A1");
            #region 保存角色信息

            sbCmdText.Append("INSERT INTO PUR_A1(PUR_A1_10,PUR_A1_20,PUR_A1_30,PUR_A1_40,PUR_A1_50,PUR_A1_60,PUR_A1_70,");
            sbCmdText.Append(sessionSQL[0]).Append(") VALUES(");
            int newRoleId = DataInterface.GetMaxId("PUR_A1", "PUR_A1_10");
            sbCmdText.Append(newRoleId.ToString()).Append(",");
            sbCmdText.Append("'").Append(msRole.roleName.Replace("'", "''")).Append("',");
            sbCmdText.Append("'").Append(msRole.roleDesc.Replace("'", "''")).Append("',");
            sbCmdText.Append("'").Append(msRole.rangeIds).Append("',");
            sbCmdText.Append("'").Append(msRole.rangeType.ToString("D")).Append("',");
            sbCmdText.Append("'").Append(msRole.sysRole.ToString("D")).Append("','0',");
            sbCmdText.Append(sessionSQL[1]).Append(")");
            lstCmdText.Add(sbCmdText.ToString());
            #endregion

            #region 保存模块管理权限

            string modPrvIds = msRole.modPrvIds;
            if (!string.IsNullOrEmpty(modPrvIds))
            {
                string[] sionModSQL = SessionExt.GetSysFieldSQL("PUR_R3");
                string[] modPrvArray = modPrvIds.Split(',');
                foreach (string eMorPrvId in modPrvArray)
                {
                    sbCmdText.Remove(0, sbCmdText.ToString().Length);
                    sbCmdText.Append("INSERT INTO PUR_R3(PUR_R3_10,PUR_R3_20,").Append(sionModSQL[0]).Append(") VALUES (");
                    sbCmdText.Append(newRoleId.ToString()).Append(",");
                    sbCmdText.Append(eMorPrvId).Append(",");
                    sbCmdText.Append(sionModSQL[1]).Append(")");
                    lstCmdText.Add(sbCmdText.ToString());
                }
            }
            #endregion

            #region 保存操作权限

            List<MsPurview> lstOperPrv = msRole.lstMenuPrv;
            string[] sionOperSQL = SessionExt.GetSysFieldSQL("PUR_R2");
            if (null != lstOperPrv && lstOperPrv.Count > 0)
            {
                foreach (MsPurview ePrv in lstOperPrv)
                {
                    sbCmdText.Remove(0, sbCmdText.ToString().Length);
                    sbCmdText.Append("INSERT INTO PUR_R2(PUR_R2_10,PUR_R2_20,PUR_R2_30,PUR_R2_40,PUR_R2_50,").Append(sionOperSQL[0]).Append(") VALUES (");
                    sbCmdText.Append(newRoleId.ToString()).Append(",");
                    sbCmdText.Append(ePrv.menuId).Append(",");
                    sbCmdText.Append("'").Append(ePrv.rangeSign).Append("',");
                    sbCmdText.Append("'").Append(ePrv.custRangeType.ToString("D")).Append("',");
                    sbCmdText.Append("'").Append(ePrv.custRangeIds).Append("',");
                    sbCmdText.Append(sionOperSQL[1]).Append(")");
                    lstCmdText.Add(sbCmdText.ToString());
                }
            }
            #endregion

            #region 如果角色有模块管理权限，那么需要把权限页面的操作权限赋给该角色
            if (!string.IsNullOrEmpty(modPrvIds))
            {
                sbCmdText.Remove(0, sbCmdText.ToString().Length);
                string prvMenuId = getPrvOperMenuId();  //获取权限菜单Id
                sbCmdText.Append("INSERT INTO PUR_R2(PUR_R2_10,PUR_R2_20,PUR_R2_30,PUR_R2_40,PUR_R2_50,").Append(sionOperSQL[0]).Append(") VALUES (");
                sbCmdText.Append(newRoleId.ToString()).Append(",");
                sbCmdText.Append(prvMenuId).Append(",NULL,NULL,NULL,");
                sbCmdText.Append(sionOperSQL[1]).Append(")");
                lstCmdText.Add(sbCmdText.ToString());
            }

            #endregion

            try
            {
                int iexe = DataAccessor.ExecuteNonQuery(lstCmdText);
                if (iexe > 0) return new List<string> { newRoleId.ToString(), "保存成功!" };
                else return new List<string> { "-1", "保存失败:服务器忙请稍后重新尝试操作!" };
            }
            catch (Exception ex)
            {
                StringBuilder sbParam = new StringBuilder();
                int sqlIndex = 1;
                foreach (string eSQL in lstCmdText)
                {
                    sbParam.Append("<SQL" + sqlIndex.ToString()).Append("><![CDATA[").Append(eSQL);
                    sbParam.Append("]]></SQL" + sqlIndex.ToString() + ">");
                    sqlIndex++;
                }
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = sbParam.ToString()
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                sbParam = null;
                return new List<string> { 
                    "-2",
                    "保存失败:详情请参见错误日志!"                    
                };
            }
        }

        /// <summary>
        /// 获取权限操作菜单Id
        /// </summary>
        /// <returns></returns>
        private string getPrvOperMenuId()
        {
            string cmdText = "SELECT PUR_B1_10 AS MENUID FROM PUR_B1 WHERE PUR_B1_90='1' AND PUR_B1_140='1'";
            string prvMenuId = string.Empty;
            try
            {
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    if (iReader.Read() && null != iReader[0])
                        prvMenuId = iReader["MENUID"].ToString();
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            return prvMenuId;
        }


        private List<string> update(MsRole msRole)
        {
            List<string> lstCmdText = new List<string>();
            StringBuilder sbCmdText = new StringBuilder();
            string cmdText = string.Empty;
            string roleId = msRole.roleId;

            #region 更新角色信息
            sbCmdText.Append("UPDATE PUR_A1 SET PUR_A1_20='").Append(msRole.roleName.Replace("'", "''")).Append("'");
            sbCmdText.Append(",PUR_A1_30='").Append(msRole.roleDesc.Replace("'", "''")).Append("'");
            sbCmdText.Append(",PUR_A1_40='").Append(msRole.rangeIds).Append("'");
            sbCmdText.Append(",PUR_A1_50='").Append(msRole.rangeType.ToString("D")).Append("' ");
            sbCmdText.Append("WHERE PUR_A1_10=").Append(roleId);
            lstCmdText.Add(sbCmdText.ToString());
            #endregion

            #region 更新模块操作权限
            cmdText = "DELETE FROM PUR_R3 WHERE PUR_R3_10=" + roleId;
            lstCmdText.Add(cmdText);

            string modPrvIds = msRole.modPrvIds;
            if (!string.IsNullOrEmpty(modPrvIds))
            {
                string[] sionModSQL = SessionExt.GetSysFieldSQL("PUR_R3");
                string[] modPrvArray = modPrvIds.Split(',');
                foreach (string eMorPrvId in modPrvArray)
                {
                    sbCmdText.Remove(0, sbCmdText.ToString().Length);
                    sbCmdText.Append("INSERT INTO PUR_R3(PUR_R3_10,PUR_R3_20,").Append(sionModSQL[0]).Append(") VALUES (");
                    sbCmdText.Append(roleId).Append(",");
                    sbCmdText.Append(eMorPrvId).Append(",");
                    sbCmdText.Append(sionModSQL[1]).Append(")");
                    lstCmdText.Add(sbCmdText.ToString());
                }
            }
            #endregion

            #region 更新角色操作权限
            /* 业务逻辑说明:
             *     根据当前设置的菜单Id来删除库中该角色对应的操作权限菜单，对于角色的其他操作权限菜单关系记录则不能够删除。
             *     这是因为角色在不同用户之间是公开的，而不同登录用户所具有的菜单分配权限是不同的，因此，用户针对某一角色的权限
             *     修改，只限于该用户所具有的分配权限菜单。而对于该角色赋予的其他菜单操作权限不能进行修改，因此也就不能先删除掉。
             *  tim 2010-03-10 */

            List<MsPurview> lstOperPrv = msRole.lstMenuPrv;
            string[] sionOperSQL = SessionExt.GetSysFieldSQL("PUR_R2");
            MsLoginUser loginUser = HttpContext.Current.Session["LogUserInfo"] as MsLoginUser;
            eUserType enUserType = loginUser.userType;
            string roleIds = (enUserType.Equals(eUserType.ORDINARY)) ? GetRoleIdsByUserId(loginUser.userId, enUserType, loginUser.organId)
                                : "ADMINROLE"; //只有非系统管理员设置权限菜单才根据以上逻辑处理,系统管理员设置权限，直接删除原有设置，重新保存
            if (!string.IsNullOrEmpty(roleIds))
            {
                if (enUserType.Equals(eUserType.ORDINARY))
                {
                    sbCmdText.Remove(0, sbCmdText.ToString().Length);
                    sbCmdText.Append("DELETE FROM PUR_R2 WHERE PUR_R2_10='").Append(roleId).Append("' AND PUR_R2_20 IN (");
                    sbCmdText.Append("SELECT A.PUR_B1_10 FROM (SELECT * FROM PUR_B1 WHERE PUR_B1_50='0'AND PUR_B1_140='0' AND PUR_B1_90='1') A ");
                    sbCmdText.Append("INNER JOIN (SELECT PUR_B1_10,PUR_B1_30 FROM PUR_B1 WHERE PUR_B1_10 IN(SELECT PUR_R3_20 FROM PUR_R3 WHERE PUR_R3_10 IN (").Append(roleIds).Append("))) B ON A.PUR_B1_30 LIKE '%' + B.PUR_B1_30 + '%')");
                    lstCmdText.Add(sbCmdText.ToString());
                }
                else
                {
                    sbCmdText.Append("DELETE FROM PUR_R2 WHERE PUR_R2_10='").Append(roleId).Append("'");
                }
                //string operMenuIds = lstOperPrv.ToString<MsPurview>("menuId");
                //if (!string.IsNullOrEmpty(operMenuIds))
                //{
                //    cmdText = "DELETE FROM PUR_R2 WHERE PUR_R2_10=" + roleId + " AND PUR_R2_20 IN (" + operMenuIds + ")";
                //    lstCmdText.Add(cmdText);
                //}
                if (null != lstOperPrv && lstOperPrv.Count > 0)
                {
                    foreach (MsPurview ePrv in lstOperPrv)
                    {
                        sbCmdText.Remove(0, sbCmdText.ToString().Length);
                        sbCmdText.Append("INSERT INTO PUR_R2(PUR_R2_10,PUR_R2_20,PUR_R2_30,PUR_R2_40,PUR_R2_50,").Append(sionOperSQL[0]).Append(") VALUES (");
                        sbCmdText.Append(roleId).Append(",");
                        sbCmdText.Append(ePrv.menuId).Append(",");
                        sbCmdText.Append("'").Append(ePrv.rangeSign).Append("',");
                        sbCmdText.Append("'").Append(ePrv.custRangeType.ToString("D")).Append("',");
                        sbCmdText.Append("'").Append(ePrv.custRangeIds).Append("',");
                        sbCmdText.Append(sionOperSQL[1]).Append(")");
                        lstCmdText.Add(sbCmdText.ToString());
                    }
                }
            }
            #endregion

            #region 如果角色有模块管理权限，那么需要把权限页面的操作权限赋给该角色
            if (!string.IsNullOrEmpty(modPrvIds))
            {
                sbCmdText.Remove(0, sbCmdText.ToString().Length);
                string prvMenuId = getPrvOperMenuId();  //获取权限菜单Id
                cmdText = "DELETE FROM PUR_R2 WHERE PUR_R2_10=" + roleId + " AND PUR_R2_20=" + prvMenuId; //有可能已经设置过了，因此先删除
                lstCmdText.Add(cmdText);

                sbCmdText.Append("INSERT INTO PUR_R2(PUR_R2_10,PUR_R2_20,PUR_R2_30,PUR_R2_40,PUR_R2_50,").Append(sionOperSQL[0]).Append(") VALUES (");
                sbCmdText.Append(roleId).Append(",");
                sbCmdText.Append("'").Append(prvMenuId).Append("',NULL,NULL,NULL,");
                sbCmdText.Append(sionOperSQL[1]).Append(")");
                lstCmdText.Add(sbCmdText.ToString());
            }

            #endregion

            try
            {
                int iexe = DataAccessor.ExecuteNonQuery(lstCmdText);
                if (iexe > 0) return new List<string> { roleId, "保存成功!" };
                else return new List<string> { "-1", "保存失败:服务器忙请稍后重新尝试操作!" };
            }
            catch (Exception ex)
            {
                StringBuilder sbParam = new StringBuilder();
                int sqlIndex = 1;
                foreach (string eSQL in lstCmdText)
                {
                    sbParam.Append("<SQL" + sqlIndex.ToString()).Append("><![CDATA[").Append(eSQL);
                    sbParam.Append("]]></SQL" + sqlIndex.ToString() + ">");
                    sqlIndex++;
                }
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = sbParam.ToString()
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                sbParam = null;
                return new List<string> { 
                    "-2",
                    "保存失败:详情请参见错误日志!"                    
                };
            }
        }

        private string getOrdinaryRoles(string userId, string organId)
        {
            List<MsRole> lstRole = getALLRole(organId);

            IUser _userProcessor = Factory.CreateObject(MsUser.assemblyName, MsUser.className, ImportComponentType.DotNetDll, null) as IUser;
            MsUser msUser = _userProcessor.GetUserInfo(userId, eTrueFalse.TRUE);

            if (null == msUser) return string.Empty;

            IEnumerable<MsRole> roleQuery = lstRole.Where(r =>
            {
                if (r.rangeType == eSysRangeType.ALL) return true;
                else
                {
                    StringLib oString = new StringLib(r.rangeIds);
                    bool bContain = false;
                    switch (r.rangeType)
                    {
                        case eSysRangeType.USER:
                            bContain = oString.Contains(msUser.userId);
                            break;
                        case eSysRangeType.DEPT:
                            bContain = oString.Contains(msUser.belongDept.deptId);
                            break;
                        case eSysRangeType.POS:
                            bContain = oString.Contains(msUser.belongPos.posId);
                            break;
                        case eSysRangeType.CLS:
                            bContain = oString.Contains(msUser.belongClass.clsId);
                            break;
                    }
                    return bContain;
                }
            });

            string roleIds = roleQuery.ToList<MsRole>().ToString<MsRole>("roleId");

            _userProcessor = null;
            lstRole = null;
            roleQuery = null;
            return roleIds;
        }

        private string getAdminRoles()
        {
            string cmdText = "SELECT PUR_A1_10 AS ROLEID FROM PUR_A1 WHERE PUR_A1_60='2' AND PUR_A1_70='0'";
            string roleIds = string.Empty;
            try
            {
                string roleId = string.Empty;
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while (iReader.Read())
                    {
                        roleId = iReader["ROLEID"].ToString();
                        roleIds += (string.IsNullOrEmpty(roleIds)) ? roleId : "," + roleId;
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            return roleIds;
        }
        #endregion
    }
}
